/********************************************************************************
* File Name:	login.cpp
* Description:	第7章实例训练
* Reference book:《Linux环境下Qt4图形界面与MySQL编程》，机械工业出版社.2012.1
* E_mail: openlinux2011@gmail.com
*
********************************************************************************/
#include "login.h"
#include "ui_login.h"
#include "mainwindow.h"

#include <QtSql/QSqlQuery>
#include <QtSql/QSqlDatabase>
#include <QMessageBox>
#include "databaseconnection.h"

login::login(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::login)
{
    ui->setupUi(this);
    ui->lineEdit_2->setEchoMode(QLineEdit::Password);
    ui->lineEdit->setText("");
}

login::~login()
{
    delete ui;
}

void login::on_btnlogin_clicked()
{
    bool success = false;
    if(!databaseconnection::Open())
    {
        QMessageBox::about(this,"Message","connect error");
        return;
    }
    else
    {
        QString user = ui->lineEdit->text().trimmed();
        QString pwd = ui->lineEdit_2->text().trimmed();
        if(user==0)
        {
            QMessageBox::about(this,"Message","please input username!");
            return;
        }
        else if(pwd == "")
        {
            QMessageBox::about(this,"Message","please input passwd!");
            return;
        }
        else
        {
            QSqlQuery query;
            if(query.exec("select * from login"))
            {
                while(query.next())
                {
                    if(user==query.value(1).toString()&&pwd==query.value(2).toString())
                    {
                         success = true;
                         databaseconnection::Close();
                         break;
                    }
                }
                if(success)
                {
                    MainWindow *m = new MainWindow();
                    m->show();
                    this->hide();
                }
                else
                {
                     QMessageBox::about(this,"Message","login fail!");
                }
             }
        }
    }
}

void login::on_btncancel_clicked()
{
    this->close();
}
